package com.cskaoyan.market.service;

import com.cskaoyan.market.annotation.CouponProvide;
import com.cskaoyan.market.application.RegisterSuccessEvent;
import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.db.domain.MarketUserExample;
import com.cskaoyan.market.db.mapper.MarketUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2024/5/18 9:52
 * @Version 1.0
 */
@Service
public class WxAuthServiceImpl implements WxAuthService, ApplicationEventPublisherAware {

    @Autowired
    MarketUserMapper userMapper;
    private ApplicationEventPublisher eventPublisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.eventPublisher = applicationEventPublisher;
    }




    @Override
    public MarketUser getByUsername(String username) {
        //利用username查询当前的用户信息
        MarketUserExample marketUserExample = new MarketUserExample();
        marketUserExample.createCriteria().andUsernameEqualTo(username);
        return userMapper.selectOneByExample(marketUserExample);
    }

    @CouponProvide
    @Override
    public MarketUser register(String username, String password, String mobile) {
        MarketUser marketUser = new MarketUser();
        marketUser.setAddTime(LocalDateTime.now());
        marketUser.setUsername(username);
        marketUser.setPassword(password);
        marketUser.setMobile(mobile);
        marketUser.setNickname(username);
        marketUser.setAvatar("https://cskaoyan.oss-cn-beijing.aliyuncs.com/c4fa7dd367d945fb87a66f551466b133.png");
        MarketUserExample marketUserExample = new MarketUserExample();
        marketUserExample.createCriteria().andMobileEqualTo(mobile);
        List<MarketUser> marketUsers = userMapper.selectByExample(marketUserExample);
        if (!marketUsers.isEmpty()) {
            return null;
        }
        userMapper.insertSelective(marketUser);
        MarketUser marketUser1 = userMapper.selectOneByExample(marketUserExample);
        // 发布注册成功事件
        eventPublisher.publishEvent(new RegisterSuccessEvent(this));
        return marketUser1;
    }

    @Override
    public void reset(String password, String mobile) {
        MarketUserExample marketUserExample = new MarketUserExample();
        marketUserExample.createCriteria().andMobileEqualTo(mobile);
        MarketUser marketUser = userMapper.selectByExample(marketUserExample).get(0);
        marketUser.setPassword(password);
        userMapper.updateByPrimaryKey(marketUser);
    }

}
